﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Text;
using PsychSurvey.Properties;

namespace PsychSurvey.Classes
{
    public class Email
    {
        public static bool SendHtmlEmail(string FromAddress
            , string ToAddress
            , string Subject
            , string Body)
        {
            MailMessage myMessage = new MailMessage(FromAddress, ToAddress, Subject, Body);
            myMessage.IsBodyHtml = true;
            SmtpClient client = new SmtpClient();
            try
            {
                client.Send(myMessage);
            }
            catch (SmtpException error)
            {
                return false;
            }
            return true;
        }
        public static bool NotifyParticipantOfSurvey(int IndividualId
            ,string EmailAddress
            ,Guid StudyId
            , int ConditionId)
        {
            //Get the study
            Study MyStudy = Study.GetStudy(StudyId);
            string StudyUrl = Study.GetStudyUrl(StudyId);
            
            dbDataContext db = new dbDataContext();
            //Gets the current page
            GetCurrentStudyLocationResult curr = db.GetCurrentStudyLocation(IndividualId, StudyId, ConditionId).FirstOrDefault();
            DateTime StudyWaveWindowClose = curr.DateStart.AddDays(curr.DayEndOffset.Value);

            string Subject = "Survey Reminder - " + MyStudy.StudyName;
            StringBuilder body = new StringBuilder();
            body.Append("A survey is available for you to complete online.<br/><br/>");
            body.Append("Please complete this survey before <b> " 
                + StudyWaveWindowClose.DayOfWeek.ToString() 
                + ", " + StudyWaveWindowClose.ToShortDateString()
                + " at " + StudyWaveWindowClose.ToShortTimeString() + "</b>.<br/><br/>");
            body.Append("<a href=\"" + StudyUrl + "\">" + StudyUrl + "</a><br/><br/>");
            body.Append("Thank for you participating in this study.");
            bool Result = SendHtmlEmail(Settings.Default.FromEmailAddress
                , EmailAddress
                , Subject
                , body.ToString());    
        
            //Report Notification
            if (Result)
            {
                StudyNotification.ReportNotification(IndividualId, StudyId, curr.StudyWaveId, DateTime.Now);
            }
            return Result;
        }
    }
}
